package com.cws.project.cws.teacher.controller;

import com.cws.common.constant.UserConstants;
import com.cws.common.utils.StringUtils;
import com.cws.common.utils.poi.ExcelUtil;
import com.cws.common.utils.security.ShiroUtils;
import com.cws.framework.aspectj.lang.annotation.Log;
import com.cws.framework.aspectj.lang.enums.BusinessType;
import com.cws.framework.web.controller.BaseController;
import com.cws.framework.web.domain.AjaxResult;
import com.cws.framework.web.page.TableDataInfo;
import com.cws.project.cws.clazz.domain.Clazz;
import com.cws.project.cws.clazz.service.IClazzService;
import com.cws.project.cws.student.domain.Student;
import com.cws.project.cws.student.service.IStudentService;
import com.cws.project.cws.teacher.domain.Teacher;
import com.cws.project.cws.teacher.service.ITeacherService;
import com.cws.project.system.role.domain.Role;
import com.cws.project.system.role.service.IRoleService;
import com.cws.project.system.user.domain.User;
import com.cws.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author XYL
 * @date 2021-12-22 9:48
 */
@Controller
@RequestMapping("/cws/teacher")
public class TeacherController extends BaseController {
    private String prefix = "cws/teacher" ;

    @Autowired
    private IUserService userService;

    @Autowired
    private ITeacherService teacherService;

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IClazzService clazzService;

    @RequiresPermissions("cws:teacher:list")
    @GetMapping()
    public String clazz() {
        return prefix + "/teacher" ;
    }

    @RequiresPermissions("cws:teacher:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Teacher tea) {
        startPage();
        User sysUser = getSysUser();
        List<Teacher> list= new ArrayList<>();
        //是否是管理员
        if(sysUser.isAdmin()) {
            tea.setUserId(null);
            list = teacherService.selectTeacherList(tea);
        }
        if(sysUser.isInstructor()){
            tea.setUserId(sysUser.getUserId());
            list = teacherService.selectTeacherList(tea);
        }
        return getDataTable(list);
    }


    @Log(title = "教师管理" , businessType = BusinessType.EXPORT)
    @RequiresPermissions("cws:teacher:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Teacher tea) {
        startPage();
        //当前辅导员id，
        User sysUser = getSysUser();
        List<Teacher> list= new ArrayList<>();
        //是否是管理员
        if(sysUser.isAdmin()) {
            tea.setUserId(null);
            list = teacherService.selectTeacherList(tea);
        }
        if(sysUser.isInstructor()){
            tea.setUserId(sysUser.getUserId());
            list = teacherService.selectTeacherList(tea);
        }
        ExcelUtil<Teacher> util = new ExcelUtil<>(Teacher.class);
        return util.exportExcel(list, "教师数据");
    }

    /**
     * 新增教师
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        User sysUser = getSysUser();
        if(sysUser.isAdmin()){
            sysUser.setUserId(null);
        }
        List<Clazz> list = clazzService.selectClazzListByUserId(sysUser.getUserId());
        mmap.put("clazzs",list);
        return prefix + "/add" ;
    }

    /**
     * 新增保存教师
     */
    @RequiresPermissions("cws:teacher:add")
    @Log(title = "教师管理" , businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated Teacher tea) {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(tea.getLoginName()))) {
            return error("新增教师'" + tea.getLoginName() + "'失败，工号已存在");
        } else if (StringUtils.isNotEmpty(tea.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(tea))) {
            return error("新增教师'" + tea.getLoginName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(tea.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(tea))) {
            return error("新增教师'" + tea.getLoginName() + "'失败，邮箱账号已存在");
        }
        return toAjax(teacherService.insertTeacher(tea));
    }

    /**
     * 修改教师
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
        User sysUser = getSysUser();
        if(sysUser.isAdmin()){
            sysUser.setUserId(null);
        }
        List<Clazz> list = clazzService.selectClazzListByUserId(sysUser.getUserId());
        mmap.put("clazzs",list);

        Teacher teacher = teacherService.selectUserById(userId);
        mmap.put("teacher" , teacher);
        return prefix + "/edit" ;
    }

    /**
     * 修改保存教师
     */
    @RequiresPermissions("cws:teacher:edit")
    @Log(title = "教师管理" , businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated Teacher tea) {
        userService.checkUserAllowed(tea);
        if (StringUtils.isNotEmpty(tea.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(tea))) {
            return error("修改教师'" + tea.getLoginName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(tea.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(tea))) {
            return error("修改教师'" + tea.getLoginName() + "'失败，邮箱账号已存在");
        }
        return toAjax(teacherService.updateTeacher(tea));
    }

    @RequiresPermissions("cws:teacher:resetPwd")
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("student" , userService.selectUserById(userId));
        return prefix + "/resetPwd" ;
    }

    @RequiresPermissions("cws:teacher:resetPwd")
    @Log(title = "重置密码" , businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(User user) {
        userService.checkUserAllowed(user);
        if (userService.resetUserPwd(user) > 0) {
            if (ShiroUtils.getUserId().longValue() == user.getUserId().longValue()) {
                setSysUser(userService.selectUserById(user.getUserId()));
            }
            return success();
        }
        return error();
    }

    /**
     * 进入授权角色页
     */
    @GetMapping("/authRole/{userId}")
    public String authRole(@PathVariable("userId") Long userId, ModelMap mmap) {
        User user = userService.selectUserById(userId);
        // 获取教师所属的角色列表
        List<Role> roles = roleService.selectRolesByUserId(userId);
        mmap.put("student" , user);
        mmap.put("roles" , User.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return prefix + "/authRole" ;
    }

    /**
     * 教师授权角色
     */
    @RequiresPermissions("cws:teacher:add")
    @Log(title = "教师管理" , businessType = BusinessType.GRANT)
    @PostMapping("/authRole/insertAuthRole")
    @ResponseBody
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    @RequiresPermissions("cws:teacher:remove")
    @Log(title = "教师管理" , businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(userService.deleteUserByIds(ids));
    }



}
